<!-- user.html -->
{% extends "base.html" %}

{% block content %}
    <div class="container dashboard">
        <div class="dashboard-sidebar">
            <h2 class="dashboard-title"><i class="fas fa-user"></i> 用户面板</h2>
            <ul class="dashboard-menu">
                <li><a href="#" class="active" onclick="showSection('weather-section')"><i class="fas fa-cloud-sun-rain"></i> 天气信息</a></li>
                <li><a href="#" onclick="showSection('response-section')"><i class="fas fa-bullhorn"></i> 应急响应</a></li>
                <li><a href="#" onclick="showSection('help-section')"><i class="fas fa-hands-helping"></i> 发送求救</a></li>
            </ul>
        </div>
        
        <div class="dashboard-content">
            <!-- 实时预警通知 -->
            <div id="real-time-alerts" class="alert-box" style="display: none;">
                <div class="alert-header">
                    <i class="fas fa-exclamation-triangle"></i> 天气预警通知
                    <button class="close-alert">&times;</button>
                </div>
                <div class="alert-content"></div>
                <div class="alert-time"></div>
            </div>

            <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
            <script>
                // 建立WebSocket连接
                const socket = io('/alerts');
                
                // 接收实时预警
                socket.on('new_alert', function(data) {
                    const alertBox = document.getElementById('real-time-alerts');
                    alertBox.querySelector('.alert-content').textContent = data.content;
                    alertBox.querySelector('.alert-time').textContent = data.timestamp;
                    alertBox.style.display = 'block';
                    
                    // 自动跳转到天气标签页
                    showSection('weather-section');
                    
                    // 自动更新天气信息
                    fetchWeatherData();
                });
                
                // 关闭警告按钮
                document.querySelector('.close-alert')?.addEventListener('click', function() {
                    document.getElementById('real-time-alerts').style.display = 'none';
                });
            </script>

            <!-- 天气信息部分 -->
            <div id="weather-section" class="dashboard-section">
                <h3 class="section-title"><i class="fas fa-cloud-sun-rain"></i> 天气预警信息</h3>
                <button id="getWeatherBtn" class="btn"><i class="fas fa-sync-alt"></i> 获取天气信息</button>
                
                <div id="weatherInfo" class="info-box weather-card mt-3"></div>
            </div>
            
            <!-- 应急响应部分 -->
            <div id="response-section" class="dashboard-section" style="display: none;">
                <h3 class="section-title"><i class="fas fa-bullhorn"></i> 应急响应信息</h3>
                <button id="getResponseBtn" class="btn"><i class="fas fa-eye"></i> 查看最新响应</button>
                <div id="responseInfo" class="info-box mt-3"></div>
            </div>
            
            <!-- 求救信息部分 -->
            <div id="help-section" class="dashboard-section" style="display: none;">
                <h3 class="section-title"><i class="fas fa-hands-helping"></i> 发送求救信息</h3>
                <div class="form-group">
                    <textarea id="helpContent" class="form-control" placeholder="输入求救信息..."></textarea>
                </div>
                <button id="sendHelpBtn" class="btn"><i class="fas fa-paper-plane"></i> 发送</button>
                <div id="helpStatus" class="mt-3"></div>
            </div>
        </div>
    </div>
    
    <script>
        // 显示/隐藏不同部分
        function showSection(sectionId, event) {
            // 隐藏所有部分
            document.querySelectorAll('.dashboard-section').forEach(section => {
                section.style.display = 'none';
            });
            
            // 显示目标部分
            document.getElementById(sectionId).style.display = 'block';
            
            // 更新菜单活动状态
            document.querySelectorAll('.dashboard-menu a').forEach(link => {
                link.classList.remove('active');
            });
            
            // 确保event存在且有currentTarget
            if (event && event.currentTarget) {
                event.currentTarget.classList.add('active');
            }
        }
        
        // 获取天气信息并更新UI的函数
        function fetchWeatherData() {
            fetch('{{ url_for("user_get_weather") }}')
                .then(response => response.json())
                .then(data => {
                    const weatherInfo = document.getElementById('weatherInfo');
                    if (data.status === 'success') {
                        let html = '<h4><i class="fas fa-cloud-sun-rain"></i> 最新天气预警</h4>';
                        if (data.data && data.data.length > 0) {
                            data.data.forEach(warning => {
                                html += `<div class="warning-item">
                                    <p><strong><i class="fas fa-exclamation-triangle"></i> 类型:</strong> ${warning.type}</p>
                                    <p><strong><i class="fas fa-shield-alt"></i> 级别:</strong> ${warning.severity}</p>
                                    <p>${warning.text}</p>
                                    <p class="text-muted small"><i class="fas fa-clock"></i> 发布时间: ${data.timestamp}</p>
                                </div>`;
                            });
                        } else {
                            html += '<p class="text-muted"><i class="fas fa-info-circle"></i> 当前没有天气预警</p>';
                        }
                        weatherInfo.innerHTML = html;
                    } else {
                        weatherInfo.innerHTML = `<p class="status-error"><i class="fas fa-times-circle"></i> ${data.message}</p>`;
                    }
                });
        }

        // 默认显示第一个部分
        document.addEventListener('DOMContentLoaded', function() {
            showSection('weather-section');
            
            // 页面加载时自动获取天气信息
            fetchWeatherData();
            
            // 设置每10分钟自动刷新天气信息
            setInterval(fetchWeatherData, 10 * 60 * 1000);
            
            // 保留手动获取按钮功能
            document.getElementById('getWeatherBtn').addEventListener('click', fetchWeatherData);
            
            // 获取应急响应信息
            document.getElementById('getResponseBtn').addEventListener('click', function() {
                fetch('{{ url_for("user_get_response") }}')
                    .then(response => response.json())
                    .then(data => {
                        const responseInfo = document.getElementById('responseInfo');
                        if (data.status === 'success') {
                            responseInfo.innerHTML = `
                                <h4><i class="fas fa-bullhorn"></i> 应急响应信息</h4>
                                <div class="alert alert-info">
                                    <p><strong><i class="fas fa-user-shield"></i> 管理员:</strong> ${data.admin_name}</p>
                                    <p>${data.content}</p>
                                    <p class="text-muted small"><i class="fas fa-clock"></i> 发布时间: ${data.timestamp}</p>
                                </div>
                            `;
                        } else {
                            responseInfo.innerHTML = `<p class="status-error"><i class="fas fa-times-circle"></i> ${data.message}</p>`;
                        }
                    });
            });
            
            // 发送求救信息
            document.getElementById('sendHelpBtn').addEventListener('click', function() {
                const content = document.getElementById('helpContent').value;
                if (!content) {
                    alert('请输入求救信息');
                    return;
                }
                
                fetch('{{ url_for("user_send_help") }}', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `content=${encodeURIComponent(content)}`
                })
                .then(response => response.json())
                .then(data => {
                    const statusDiv = document.getElementById('helpStatus');
                    if (data.status === 'success') {
                        statusDiv.innerHTML = '<p class="status-success"><i class="fas fa-check-circle"></i> 求救信息发送成功</p>';
                        document.getElementById('helpContent').value = '';
                    } else {
                        statusDiv.innerHTML = `<p class="status-error"><i class="fas fa-times-circle"></i> ${data.message}</p>`;
                    }
                });
            });
        });
    </script>
{% endblock %}